from django.core.management.base import BaseCommand
from django.db import transaction
import random

from violation.models import Violation, JobAuditRecord


class Command(BaseCommand):
    help = "以更真实的中文数据填充 Violation(500) 与 JobAuditRecord(50)。"

    def add_arguments(self, parser):
        parser.add_argument("--force", action="store_true", help="强制重建：清空表后重新生成目标数量")
        parser.add_argument("--batch", type=int, default=200, help="bulk_create 批大小")

    def handle(self, *args, **options):
        force = options.get("force", False)
        batch_size = options.get("batch", 200)

        if force:
            Violation.objects.all().delete()
            JobAuditRecord.objects.all().delete()

        self._seed_violation(target=500, batch_size=batch_size)
        self._seed_job_audit_record(target=50, batch_size=batch_size)

    def _seed_violation(self, target: int, batch_size: int):
        existing = Violation.objects.count()
        if existing >= target:
            self.stdout.write(f"Violation 已有 {existing} 条，跳过。")
            return

        # 更真实的违规关键词库（基础短语 + 变体组合，覆盖常见灰黑产、广告引流、涉黄低俗等）
        base_terms = [
            "高薪日结", "刷单返利", "网络赌博", "六合彩", "代开发票", "发票代开", "代办学历",
            "免押金入职", "色聊兼职", "裸聊兼职", "兼职返利", "保过包过", "学历提升保过",
            "办证刻章", "有偿收购账号", "实名账号买卖", "引流加微", "扫码加群", "羊毛薅羊毛",
            "医美整形返现", "博彩推广", "外围下注", "赌场荷官招聘", "裸条借贷", "套路贷",
            "校园贷", "714 高炮", "股票内线消息", "虚假中奖", "刷粉刷赞", "互关涨粉",
            "引流变现", "色情直播", "擦边直播", "招嫖卖淫", "迷奸药出售", "代孕联系",
            "走私代购", "海淘免税", "烟卡香烟代购", "外挂脚本", "破解软件贩卖", "盗版账号共享",
            "N 号房资源", "涉政敏感词传播", "境外势力拉群", "翻墙 VPN 出售", "翻墙服务",
            "网贷协商代办", "信用卡代还", "公积金代提", "蚂蚁花呗套现", "京东白条套现",
            "招兼职日入千元", "招代理高返佣", "博彩拉新", "博彩注册返现", "代写论文",
            "代做作业", "考研资料走私", "考试答案出售", "带车跑滴滴无资质", "跑分平台",
            "洗钱跑分", "卡商收卡", "二清 POS", "色情交友群", "援交信息", "外围女资源",
            "违法药品出售", "违禁品交易", "枪支弹药购买", "弓弩购买", "开锁配钥匙无证",
        ]
        variants_prefix = ["快速", "稳定", "长期", "正规", "内部", "官方", "一对一", "保密", "下架前", "限时"]
        variants_suffix = ["渠道", "技术", "资源", "入口", "名单", "教程", "方案", "路子", "合作", "对接"]

        words = set(base_terms)
        # 组合生成更大规模但看起来像真实“话术”的词条
        while len(words) < target:
            w = f"{random.choice(variants_prefix)}{random.choice(base_terms)}{random.choice(variants_suffix)}"
            words.add(w)

        words = list(words)[:target]

        mapping_type = {
            1: ["虚假招聘", "代办、办证", "学历保过", "刷单返利"],
            2: ["涉政敏感", "境外拉群", "翻墙服务"],
            3: ["色情低俗", "招嫖卖淫", "色聊裸聊"],
            4: ["暴力违法", "枪支弹药", "违禁品"],
            5: ["广告引流", "加微拉群", "引流变现"],
        }

        def guess_type(term: str) -> int:
            term_map = {
                1: ["招聘", "代办", "办证", "学历", "刷单"],
                2: ["涉政", "境外", "翻墙", "VPN"],
                3: ["色情", "裸聊", "招嫖", "援交", "直播"],
                4: ["枪支", "弹药", "违禁", "走私"],
                5: ["引流", "加微", "扫码", "返现", "涨粉"],
            }
            for k, kws in term_map.items():
                if any(kw in term for kw in kws):
                    return k
            return random.randint(1, 5)

        to_create = []
        for term in words:
            to_create.append(
                Violation(
                    word=term,
                    word_type=guess_type(term),
                    status=1,
                )
            )

        with transaction.atomic():
            Violation.objects.bulk_create(to_create, batch_size=batch_size, ignore_conflicts=True)
        self.stdout.write(self.style.SUCCESS(f"插入 {len(to_create)} 条 Violation（目标 {target}）。"))

    def _seed_job_audit_record(self, target: int, batch_size: int):
        existing = JobAuditRecord.objects.count()
        if existing >= target:
            self.stdout.write(f"JobAuditRecord 已有 {existing} 条，跳过。")
            return

        job_titles = [
            "后端开发工程师", "前端开发工程师", "测试工程师", "数据分析师", "算法工程师",
            "产品经理", "运营专员", "新媒体运营", "电商运营", "短视频编导",
            "直播运营", "销售顾问", "客户成功经理", "客服专员", "渠道拓展",
            "人力资源专员", "招聘专员", "财务会计", "出纳", "税务专员",
            "UI 设计师", "平面设计师", "视觉设计", "交互设计师", "品牌公关",
            "行政专员", "采购专员", "仓储管理员", "物流专员", "供应链计划",
        ]
        companies = [
            "光冉科技", "星汉数据", "润溪互动", "未央智能", "澜岳网络",
            "凌越信息", "墨海数科", "晟翌科技", "岚图互动", "山海数智",
            "远瞻资本", "恒岳集团", "鸿云电商", "云迹传媒", "逐星科技",
        ]
        desc_templates = [
            "负责{title}相关模块的设计与开发，参与需求评审与技术方案制定，推动项目按期上线。",
            "参与{title}日常工作，进行数据分析与报表产出，协助产品与运营优化策略。",
            "配合团队完成{title}任务，优化性能与稳定性，持续改进用户体验。",
            "围绕{title}开展业务支持与跨部门协作，输出可落地的解决方案。",
        ]
        illegal_inject = [
            None,
            "（禁止：高薪日结、刷单返利、扫码进群等违规招录话术）",
            "（岗位严禁涉黄涉赌、广告引流、代办业务等违法内容）",
            None,
        ]

        to_create = []
        for i in range(target):
            title = random.choice(job_titles)
            company = random.choice(companies)
            job_title = f"{company}｜{title}"
            base_desc = random.choice(desc_templates).format(title=title)
            extra = random.choice(illegal_inject) or ""
            job_description = base_desc + extra
            audit_content = f"{job_title} - {job_description}"

            # 少量样本包含命中词，便于审计链路验证
            if random.random() < 0.3:
                illegal_words = random.choice(["高薪日结,刷单返利", "色情直播,擦边直播", "博彩推广,注册返现"]) 
                word_types = random.choice(["虚假招聘,广告引流", "色情低俗", "广告引流"]) 
                audit_result = random.choice([2, 3])  # 违规或可疑
            else:
                illegal_words = None
                word_types = None
                audit_result = random.choice([0, 1])  # 待审核或合规

            to_create.append(
                JobAuditRecord(
                    job_id=100000 + i + 1,
                    company_id=5000 + (i % 100),
                    job_title=job_title,
                    job_description=job_description,
                    audit_content=audit_content,
                    illegal_words=illegal_words,
                    word_types=word_types,
                    audit_result=audit_result,
                )
            )

        with transaction.atomic():
            JobAuditRecord.objects.bulk_create(to_create, batch_size=batch_size)
        self.stdout.write(self.style.SUCCESS(f"插入 {len(to_create)} 条 JobAuditRecord（目标 {target}）。"))


